<template>
  <!--
   action:	必选参数，上传的地址(自动上传) 人资中是手动上传
   show-file-list: 是否展示文件列表
   before-upload: 在图片上传前触发(上传前的校验)
  -->
  <el-upload
    class="avatar-uploader"
    action=""
    :show-file-list="false"
    :before-upload="beforeAvatarUpload"
    :http-request="handleUpload"
  >
    <img v-if="value" :src="value" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon" />
  </el-upload>
</template>

<script>
import COS from 'cos-js-sdk-v5'
export default {
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  methods: {
    // 1. 上传前校验
    beforeAvatarUpload(file) {
      // 1.1 图片的类型
      // png jpg gif bmp
      const isPic = ['image/jpeg', 'image/png', 'image/gif', 'image/bmp'].includes(file.type)
      // 1.2 图片大小
      // 1KB = 1024B  1MB = 1024KB
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isPic) {
        this.$message.error('上传头像图片只能是 JPG PNG GIF BMP 格式!')
      }
      if (!isLt5M) {
        this.$message.error('上传头像图片大小不能超过 5MB!')
      }
      return isPic && isLt5M
    },
    // 2. 自定义上传图片
    handleUpload(obj) {
      // 2.1 创建上传实例对象
      const cos = new COS({
        SecretId: 'AKIDzrXzDGDzWr0ue3EE6uU1VnupDVfkcFdG',
        SecretKey: 'gBbySpBPQF6rRq393l6PVK10qj3DFVaV'
      })
      // 2.2 调用上传文件的方法
      cos.putObject({
        Bucket: 'heima-hrsass-109-1312445828', // 存储桶名称
        Region: 'ap-shanghai', // 存储他所在地域
        Key: Date.now() + '-' + obj.file.name, // 文件名称
        StorageClass: 'STANDARD', // 标准存储
        Body: obj.file,
        onProgress: (progressData) => {
          console.log(JSON.stringify(progressData))
        }
      }, (err, data) => {
        console.log(data)
        if (data.statusCode === 200 && data.Location) {
          this.$emit('input', 'https://' + data.Location)
        } else {
          this.$message.error(err.message)
        }
      })
    }
  }
}
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
